package com.ly.web.controller.king;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.KingBaseInventoryStatusEntity;
import com.ly.heart.domain.KingOrgEntity;
import com.ly.heart.domain.king.base.BaseModelBo;
import com.ly.heart.domain.king.base.InventoryStatusBo;
import com.ly.heart.domain.request.KingBaseRequest;
import com.ly.heart.domain.response.KingBaseResponse;
import com.ly.heart.domain.response.KingBaseResponseError;
import com.ly.heart.domain.response.KingBaseResponseSuccessEntity;
import com.ly.heart.service.IKingBaseInventoryStatusService;
import com.ly.heart.service.IKingOrgService;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.heart.util.KingCommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Api (value = "InventoryStatusRemote", tags = "推基础数据-库存状态")
@RestController
@RequestMapping ("/heart/InventoryStatusRemote")
@Slf4j
public class InventoryStatusRemote {

    @Resource
    private IKingBaseInventoryStatusService iKingBaseInventoryStatusService;
    @Resource
    private IKingOrgService iKingOrgService;

    @ApiOperation ("同步拉取金蝶仓库")
    @RequestMapping ("pull")
    public AjaxResult queryList () {
        //使用接口参数的方式配置金蝶
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity::getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        /**
         * 参数顺序：
         * 编码，名称，类型，描述，可使用，MRP可用，不可销售，参与预警，不可领用，可锁库
         */
        String jsonData = "{\"FormId\":\"" + KingConstUtil.BD_StockStatus + "\",\"FieldKeys\":\"FNumber,FName,FType,FDescription,FAvailable,FAvailableMRP,FNotSale,FAvailableAlert,FNotGet,FAvailableLock\",\"FilterString\":[],\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
        try {
            //调用接口
            List<List<Object>> lists = client.executeBillQuery ( jsonData );
            for ( int i = 0; i < lists.size (); i++ ) {
                List<Object> objects = lists.get ( i );
                //根据code查询是否已存在该结算方式
                String bizCode = (String) objects.get ( 0 );
                KingBaseInventoryStatusEntity one = iKingBaseInventoryStatusService.getOne ( new LambdaQueryWrapper<KingBaseInventoryStatusEntity> ().eq ( KingBaseInventoryStatusEntity :: getInventoryStatusCode, bizCode ) );
                if ( one == null ) {
                    one = new KingBaseInventoryStatusEntity ();
                    one.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                    one.setInventoryStatusCode ( bizCode );
                    one.setCreateOrg ( CurrentUserUtil.getCompanyId () );
                    one.setUseOrg ( CurrentUserUtil.getCompanyId () );
                    one.setInventoryStatusName ( String.valueOf ( objects.get ( 1 ) ) );
                    one.setType ( String.valueOf ( objects.get ( 2 ) ) );
                    one.setDescInfo ( String.valueOf ( objects.get ( 3 ) ) );
                    Boolean isUsed = (Boolean) objects.get ( 4 );
                    one.setIsUse ( isUsed );
                    Boolean mrp = (Boolean) objects.get ( 5 );
                    one.setIsMrp ( mrp );
                    Boolean noSale = (Boolean) objects.get ( 6 );
                    one.setIsDisabledSale ( noSale );
                    Boolean warning = (Boolean) objects.get ( 7 );
                    one.setIsWarning ( warning );
                    Boolean apply = (Boolean) objects.get ( 8 );
                    one.setIsDisabledApply ( apply );
                    Boolean isInventory = (Boolean) objects.get ( 8 );
                    one.setIsInventory ( isInventory );
                    one.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
                    one.setCreateTime ( DateUtils.getNowDate () );
                    one.setState ( ConstUtil.STATE_FINISH );
                    one.setIsSend ( KingConstUtil.KING_DATA_IS_SEND_YES );
                    iKingBaseInventoryStatusService.save ( one );
                }
            }
        } catch ( Exception e ) {
            throw new RuntimeException ( "库存状态失败" );
        }
        return AjaxResult.success ( "库存状态成功" );
    }


    /**
     * 同步所有结算方式到金蝶
     * @return
     */
    @ApiOperation ("同步发送库存状态金蝶")
    @RequestMapping ("push")
    public AjaxResult push () throws Exception {
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity::getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        List<KingBaseInventoryStatusEntity> list = iKingBaseInventoryStatusService.list ( new LambdaQueryWrapper<KingBaseInventoryStatusEntity> ().
                eq ( KingBaseInventoryStatusEntity :: getIsSend, KingConstUtil.KING_DATA_IS_SEND_NO ) );
        if ( CollectionUtils.isEmpty ( list ) ) {
            return AjaxResult.error ( "暂无新数据可推！" );
        }
        batchSave ( list, client );
        submit ( list, client );
        audit ( list, client );
        return AjaxResult.success ( "推送仓库成功。" );
    }


    /**
     * 推送结算方式
     * @param list
     * @param client
     * @throws Exception
     */
    private void batchSave (List<KingBaseInventoryStatusEntity> list, K3CloudApi client) throws Exception {
        KingBaseRequest request = new KingBaseRequest ();
        List<BaseModelBo> bos = new ArrayList<> ();
        list.forEach ( inventoryStatus -> {
            InventoryStatusBo bo = new InventoryStatusBo ();
            bo.setFNumber ( inventoryStatus.getInventoryStatusCode () );
            bo.setFName ( inventoryStatus.getInventoryStatusName () );
            bo.setFType ( inventoryStatus.getType () );
            if ( StringUtils.isNotBlank ( inventoryStatus.getDescInfo () ) ) {
                bo.setFDescription ( inventoryStatus.getDescInfo () );
            }
            bo.setFAvailable ( inventoryStatus.getIsUse () );
            bo.setFAvailableMRP ( inventoryStatus.getIsMrp () );
            bo.setFNotSale ( inventoryStatus.getIsDisabledSale () );
            bo.setFAvailableAlert ( inventoryStatus.getIsWarning () );
            bo.setFNotGet ( inventoryStatus.getIsDisabledApply () );
            bo.setFAvailableLock ( inventoryStatus.getIsInventory () );
            bos.add ( bo );
        } );
        request.setModel ( bos );
        String s = JSONObject.toJSONString ( request );
        log.info ( "bos-》{}", bos );
        log.info ( "s->{}", s );
        String resultJson = client.batchSave ( KingConstUtil.BD_StockStatus, s );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //添加成功，进行提交
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "库存状态-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 推送成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "库存状态-推送失败：【" + sb + "】" );
        }
    }


    /**
     * 提交结算方式
     * @param list
     * @param client
     */
    private void submit (List<KingBaseInventoryStatusEntity> list, K3CloudApi client) throws Exception {
        InventoryStatusBo bo = new InventoryStatusBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( inventoryStatusEntity -> {
            strings.add ( inventoryStatusEntity.getInventoryStatusCode () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.submit ( KingConstUtil.BD_StockStatus, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //提交成功
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "库存状态-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.error ( "{} 提交成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "库存状态提交失败：【" + sb + "】" );
        }
    }

    /**
     * 结算方式审核
     * @param list
     * @param client
     */
    private void audit (List<KingBaseInventoryStatusEntity> list, K3CloudApi client) throws Exception {
        InventoryStatusBo bo = new InventoryStatusBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( bankEntity -> {
            strings.add ( bankEntity.getInventoryStatusCode () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.audit ( KingConstUtil.BD_StockStatus, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "库存状态-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 审核成功", sb );
            //修改为已推送状态
            list.forEach ( ware -> {
                iKingBaseInventoryStatusService.update ( new LambdaUpdateWrapper<KingBaseInventoryStatusEntity> ().
                        set ( KingBaseInventoryStatusEntity :: getIsSend, KingConstUtil.KING_DATA_IS_SEND_YES ).
                        eq ( KingBaseInventoryStatusEntity :: getId, ware.getId () ) );
            } );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "库存状态审核失败：【" + sb + "】" );
        }
    }

}
